using System;
using System.Collections.Generic;
using System.Text;
using ThaiLanguageTools.DataStruct;

namespace ThaiLanguageTools.DataParsing
{
    public class XDictMergeHelper
    {
        /// <summary>
        /// Merge several dictionaries
        /// </summary>
        /// <param name="saveFile"></param>
        /// <param name="sourceLang">Source language. Pass null for any language.</param>
        /// <param name="dictionaries"></param>
        public void Merge(String saveFile, String sourceLang, params XDict[] dictionaries)
        {
            XDict baseDict = new XDict();
            foreach (XDict d in dictionaries)
            {
                MergeTwo(sourceLang, baseDict, d);
            }
            baseDict.Entries.Sort();

            baseDict.Save(saveFile);
        }

        void MergeTwo(String sourceLang, XDict baseDict, XDict toAdd)
        {
            int firstHeaderIndex = baseDict.Headers.Count;
            baseDict.Headers.AddRange(toAdd.Headers);

            foreach (XDictEntry e in toAdd.Entries)
            {
                if (sourceLang == null || e.Word.Language == sourceLang)
                {
                    // Update the source index to point to correct header when merging
                    e.SourceIndex = firstHeaderIndex + e.SourceIndex;
                    baseDict.AddEntry(e);
                }
            }
        }

    }
}
